class Base_ClientsManager {
    constructor() {
        this.onlines = {}; //在线的连接{"1": {WsClient对象}}
        this.endId = 1;
    }

    // 获取在线连接数
    get length(){
        return Object.keys(this.onlines).length;
    }

    // 添加客户端连接
    add(client) {
        client.id = this.endId;
        this.endId ++;
        this.onlines[client.id] = client;
        return true;
    }

    // 移除客户端连接
    remove(client) {
        delete this.onlines[client.id];
        return true;
    }

    broadcast(rawmsg){
        this.forEach((client)=>{
            client.send(rawmsg);
        });
    }

    // 遍历执行函数
    forEach(func, exceptId=[]){
        if (typeof func !== 'function') {
            throw new TypeError('First argument must be a function');
        }
        if (!Array.isArray(exceptId)) {
            exceptId = [exceptId];
        }
        exceptId = exceptId.map(id=>id.toString());
        for (let id in this.onlines){
            if (exceptId.includes(id)){continue;}
            func(this.onlines[id]);
        }
    }
}

class Base_ClientManager {
    constructor(ws){
        this.ws =  ws;  // 该玩家的ws连接
        this.id = null;
    }

    send(rawmsg){
        if (this.ws.readyState != 1){
            return;
        }
        return this.ws.send(rawmsg);
    }
}

module.exports = {
    Base_ClientsManager,
    Base_ClientManager
};
